<?php

Yii::import('ext.Hq.HqController.HqController');

class LogController extends HqController
{
	public function actionIndex()
	{
		$model=new Item('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Item']))
			$model->attributes=$_GET['Item'];

		$this->render('index',array(
			'model'=>$model,
		));
	}

	/*Hàm này show ra sự thay đổi của 2 phiên bản*/
	public function actionShowDiff($pre_id,$after_id)
	{
		if($pre_id>$after_id){
			$pre_id=$pre_id+$after_id;
			$after_id=$pre_id-$after_id;
			$pre_id=$pre_id-$after_id;
		}

		$preModel=Revision::model()->findByPk($pre_id);
		$afterModel=Revision::model()->findByPk($after_id);

		$preValue=json_decode($preModel->value,true);
		$afterValue=json_decode($afterModel->value,true);

		$comparePreAfter=array_diff($preValue,$afterValue);
		$compareAfterPre=array_diff($afterValue,$preValue);

		$keyBefore=array_keys($preValue);
		$keyAfter=array_keys($afterValue);

		$onlyAfter = array_diff($keyAfter, $keyBefore);
		$onlyBefore = array_diff($keyBefore, $keyAfter);
		$both = array_intersect($keyAfter, $keyBefore);

		$keys = array_merge($onlyBefore, $onlyAfter);
		$keys = array_merge($keys, $both);
		sort($keys);

		$item=$preModel->item;

		$this->render('show_diff',array(
			'preModel'=>$preModel,
			'afterModel'=>$afterModel,
			'keys'=>$keys,
			'onlyAfter'=>$onlyAfter,
			'onlyBefore'=>$onlyBefore,
			'both'=>$both,
			'item'=>$item,
		));
	}

	public function actionCompareBefore($id,$item_id)
	{
		$item=Item::model()->findByPk($item_id);

		foreach($item->revisions_asc as $revision)
		{
			$keyRevision[]=$revision->id;
			if($revision->id==$id) break;
		}

		$find=array_search($id,$keyRevision);
		if($find==0)
			$this->redirect($this->createUrl('item/view',array('id'=>$item_id)));

		$after_id=$id;

		$pre_id=$keyRevision[$find-1];

		$this->redirect($this->createUrl('log/showDiff',array(
					'pre_id'=>$pre_id,
					'after_id'=>$after_id
				)));

	}

	/*Hàm này so sánh phiên bản có id là $id và phiên bản ngay sau nó của cùng item*/
	public function actionCompareAfter($id,$item_id)
	{
		$item=Item::model()->findByPk($item_id);

		foreach($item->revisions as $revision)
		{
			$keyRevision[]=$revision->id;
			if($revision->id==$id) break;
		}

		$find=array_search($id,$keyRevision);

		if($find==0)
			$this->redirect($this->createUrl('item/view',array('id'=>$item_id)));

		$after_id=$id;

		$pre_id=$keyRevision[$find-1];

		$this->redirect($this->createUrl('log/showDiff',array(
				'pre_id'=>$pre_id,
				'after_id'=>$after_id
			)));

	}


}
?>
